# -*- coding:UTF-8 -*-
from init.confighelper import ConfigHelper
from helpers.filehelper import FileHelper
from mainprocess import *
from tests.XML_Test import xml_test
from helpers.udphelper import UdpHelper
from init.fileinit import load_keyfile, set_devicename
from init.socketinit import im_init

import xml


def main():
    udp_h = UdpHelper()
    while True:
        im_server_str = udp_h.run()
        udp_h.close()
        
        im_server_meta = json.loads(im_server_str)
        if im_init(im_server_meta["server_ip"], im_server_meta["server_port"]) == False:
            continue
        else:
            break
    
    load_keyfile()
    set_devicename()

    from init.fileinit import device_key, device_name
    file_h = FileHelper()
    
    path = file_h.download_xml(im_server_meta["server_ip"], im_server_meta["server_port"], device_key, device_name)
    
    dom = xml.dom.minidom.parse(path)
    x = dom.documentElement
    conf_h = ConfigHelper(x)
    
    tcp_h = TcpHelper(im_server_meta["server_ip"], im_server_meta["server_port"])
    tcp_h.login()
    main_process(tcp_h)


if __name__ == "__main__":
    main()
